import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_channel_demo/utils/tools.dart';
import 'package:flutter_channel_demo/api/contracts.dart';
import 'package:flutter_channel_demo/widgets/popUp.dart';
import 'package:flutter_channel_demo/widgets/top_filter.dart';

const List<dynamic> statusList = [
  {'name': '待签署', 'id': 'WAITSIGN'},
  {'name': '签署中', 'id': 'PART'},
  {'name': '已签署', 'id': 'SIGNED'},
  {'name': '签署失败', 'id': 'FAILED'}
];
const int contractType = 2; // 合同类型，BtoC合同

class Contracts extends StatefulWidget {
  final Map? arguments;

  const Contracts({super.key, this.arguments});

  @override
  State<Contracts> createState() => _ContractsState();
}

class _ContractsState extends State<Contracts>
    with AutomaticKeepAliveClientMixin {
  dynamic contractStatus = statusList[0]['id']; //statusList[0]['value'];

  //ScrollController可以监听滑动事件，判断当前view所处的位置
  final ScrollController _scrollController = ScrollController();
  final GlobalKey _stackKey = GlobalKey();

  // List<dynamic> listData = [];
  List<dynamic> contractsList = [];
  final pageSize = 10;
  int currentPage = 1;
  var listTotal = 0;
  bool loading = false;
  bool loadMore = false;

  @override
  bool get wantKeepAlive => true; // 是否开启缓存

  @override
  void initState() {
    super.initState();

    if (widget.arguments != null && widget.arguments!.containsKey('status')) {
      contractStatus = widget.arguments?['status'];
    }

    // 初始化数据
    requestList();

    //设置监听
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print('滑动到了最底部');
        _getMore();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: const Text('合同列表'),
        ),
        body: TopFilter(
          stackKey: _stackKey,
          showAll: false,
          options: statusList,
          content: listContentBuilder(),
          defaultSelectionIdx: 0,
          itemTap: (condition) {
            setState(() {
              contractStatus = condition?.value!;
              currentPage = 1;
              requestList();
            });
          },
        ));
  }

  Widget listContentBuilder() {
    if (loading) {
      return const Padding(padding: EdgeInsets.all(10.0));
    }
    return Expanded(
        child: RefreshIndicator(
      onRefresh: _onRefresh,
      child: ListView.builder(
        itemCount: contractsList.length + 1,
        controller: _scrollController,
        itemBuilder: contractItemBuilder,
      ),
    ));
  }

  Widget contractItemBuilder(context, int index) {
    if (contractsList.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            Image.network(
              'https://img01.yzcdn.cn/vant/empty-image-default.png',
              width: 160,
              height: 160,
            ),
            const Text(
              "暂无数据",
              style: TextStyle(fontSize: 14),
            ),
          ],
        ),
      );
    } else if (index < contractsList.length) {
      // / 合同发期时间
      var createTime = (DateTime.fromMillisecondsSinceEpoch(
              contractsList[index]['CreateOn'] * 1000))
          .toString()
          .substring(0, 19);
      // 合同签署截止日期
      var deadLine = (DateTime.fromMillisecondsSinceEpoch(
              int.parse(contractsList[index]['DeadLine']) * 1000))
          .toString()
          .substring(0, 19);

      return GestureDetector(
          onTap: () => _openContract(context, index), // 跳转到合同页
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Card(
              child: Flex(
                direction: Axis.horizontal,
                children: [
                  Expanded(
                    flex: 4,
                    child: Container(
                      padding:
                          const EdgeInsets.only(left: 10, top: 8.0, bottom: 12),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('${contractsList[index]['FlowName']}',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.labelLarge),
                          const SizedBox(
                            height: 5.0,
                          ),
                          Text("合同发起时间：$createTime",
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: Theme.of(context).textTheme.labelMedium),
                          const SizedBox(
                            height: 5.0,
                          ),
                          Visibility(
                              maintainAnimation: true,
                              maintainState: true,
                              maintainSize: false,
                              visible: ['INIT', 'PART', 'WILLEXPIRE']
                                  .contains(contractsList[index]['FlowStatus']),
                              child: Text("合同截止日期：$deadLine",
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style:
                                      Theme.of(context).textTheme.labelMedium)),
                        ],
                      ),
                    ),
                  ),
                  Expanded(flex: 1, child: statusWidget(index)),
                ],
              ),
            ),
          ));
    } else if (index == listTotal && listTotal != 0) {
      return const Padding(
          padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
          child: Text(
            '没有更多了',
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey),
          ));
    } else {
      return loadMoreWidget();
    }
  }

  // 状态显示
  Widget statusWidget(int index) {
    // 合同状态
    String statusText = '';
    var statusBgColor = Colors.green;
    dynamic listStatus = contractsList[index]['FlowStatus'] ?? '';
    if (listStatus == 'PART') {
      statusText = '签署中';
      statusBgColor = Colors.orange;
    } else if (['INIT', 'PART', 'WILLEXPIRE'].contains(listStatus)) {
      statusText = '待签署';
      statusBgColor = Colors.orange;
    } else if (listStatus == 'ALL') {
      statusText = '已签署';
      statusBgColor = Colors.green;
    } else {
      statusText = '签署失败';
      statusBgColor = Colors.red;
    }

    return Container(
      margin: const EdgeInsets.only(right: 20.0, left: 20.0),
      padding: const EdgeInsets.only(top: 5.0, bottom: 5.0),
      decoration: BoxDecoration(
          color: statusBgColor,
          borderRadius: const BorderRadius.all(Radius.circular(3))),
      child: Center(
          child: Text(statusText,
              maxLines: 1,
              style: Theme.of(context)
                  .textTheme
                  .labelSmall!
                  .copyWith(color: Colors.white))),
    );
  }

  // 加载更多时显示
  Widget loadMoreWidget() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              '加载中...     ',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  // 请求列表
  Future requestList() async {
    if (!loading) {
      setState(() {
        loading = true;
      });

      try {
        dynamic listRes = await fetchContractList(contractType, pageSize,
            (currentPage - 1) * pageSize, contractStatus, context);
        List<dynamic> listData = listRes['data']['contracts'];
        // 更新数据
        setState(() {
          listTotal = listRes['data']['totalCount'];
          if (loadMore) {
            contractsList = [...contractsList, ...listData];
            currentPage++;
          } else {
            contractsList = [...listData];
          }

          loadMore = listTotal > contractsList.length ? true : false;
          loading = false;
        });
        // print('合同列表： $contractsList');
      } catch (e) {
        print('合同列表请求失败：: $e');
      } finally {
        setState(() {
          loading = false;
        });
      }
    }
  }

  // onRefresh 下拉刷新方法,为list重新赋值
  Future _onRefresh() async {
    await Future.delayed(const Duration(seconds: 1), () {
      print('refresh');
      currentPage = 1;
      requestList();
    });
  }

  //  上拉加载更多
  Future _getMore() async {
    await Future.delayed(const Duration(seconds: 1), () {
      print('加载更多');
      requestList();
    });
  }

  Future _openContract(context, int index) async {
    dynamic flowApproverInfos =
        json.decode(contractsList[index]['FlowApproverInfos']);
    if (contractsList[index]['FlowStatus'] == 'PART' &&
        flowApproverInfos[1]['ApproveStatus'] == 'ACCEPT') {
      return false;
    }

    if (['INIT', 'PART', 'WILLEXPIRE']
        .contains(contractsList[index]['FlowStatus'])) {
      try {
        // 待签署/签署中 状态下 可以点击跳转到合同页面
        dynamic response = await createH5SignUrl(
            {'flowId': contractsList[index]['FlowId']}, context);
        print('signUrlRes====$response');
        if (response['code'] == 20000) {
          dynamic flowUrlInfos = response['data']['FlowApproverUrlInfos'];
          dynamic signUrl = flowUrlInfos[0]['SignUrl'];
          // print('signUrl====$signUrl');
          Navigator.pushNamed(context, '/webview',
              arguments: {'url': signUrl, 'title': '签署合同'});
        } else {
          showAlertPopup(context, '提示', response['message'], '确定');
          print(response['message']);
        }
      } catch (e) {
        print('合同跳转链接生成失败：: $e');
      }
    }
  }
}
